package com.ai.nsa;

import com.ai.nsa.utils.LeftPad;
import com.ai.nsa.utils.hbase.model.HBaseRow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Feng Chen 2017/6/12.
 */
public class DefaultNSAPage implements NSAPage {

    private String prefix;

    private int pageSize;

    private int totalPage;

    private List<HBaseRow> rows;

    public DefaultNSAPage() {
    }

    public DefaultNSAPage(String prefix, int pageSize, List<HBaseRow> rows) {
        this.prefix = prefix;
        this.pageSize = pageSize;
        this.rows = rows;
    }

    public String getPrefix() {
        return prefix;
    }

    public DefaultNSAPage setPrefix(String prefix) {
        this.prefix = prefix;
        return this;
    }

    public int getPageSize() {
        return pageSize;
    }

    public DefaultNSAPage setPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }

    public synchronized int getTotalPage() {
        return totalPage;
    }

    public List<HBaseRow> getRows() {
        return rows;
    }

    public DefaultNSAPage setRows(List<HBaseRow> rows) {
        this.rows = rows;
        return this;
    }

    public synchronized Map<String, List<HBaseRow>> page() {

        // 总页数
        totalPage = (int) Math.ceil((rows.size() * 1.0) / pageSize);
        Map<String, List<HBaseRow>> pages = new HashMap<String, List<HBaseRow>>();

        // 生成分页
        for (int n = 1; n <= totalPage; n++) {
            String key = key(prefix, n);
            List<HBaseRow> page = new ArrayList<HBaseRow>();
            for (int s = ((n - 1) * 3); (s <= (n * 3 - 1) && s < rows.size()); s++) {
                page.add(rows.get(s));
            }
            pages.put(key, page);
        }
        return pages;
    }


    // SECTION: INNER HELPER

    private String key(String prefix, int page) {
        return prefix + NSAConstants.UNDERLINE + LeftPad.pad(page, 4, "0");
    }


}
